﻿using System.Drawing;
using System.Drawing.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace RealTimeCharts.LineChart
{
    public class BitmapBuffer
    {
        private WriteableBitmap wBitmap = null;
        private Bitmap backBitmap = null;
        private Graphics gs = null;

        public int width = 0;
        public int height = 0;

        public BitmapBuffer() { }

        public BitmapBuffer(int width, int height)
        {
            this.width = width;
            this.height = height;

            // 绑定writeable bitmap 到image
            wBitmap = new WriteableBitmap((int)width, (int)height, 96, 96, PixelFormats.Bgra32, null);

            // 根据writable bitmap 生成一个bitmap，用于二级缓存， 并且能够使用Graphis接口绘制 （Format32bppRgb)
            backBitmap = new Bitmap(width, height, wBitmap.BackBufferStride, System.Drawing.Imaging.PixelFormat.Format32bppArgb,wBitmap.BackBuffer);
        }

        public Graphics CreateGraphics()
        {
            Graphics gs = Graphics.FromImage(backBitmap);
            // 将TextRenderingHint属性设为AntiAliasGridFit，去除汉字的描边效果
            gs.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
            return gs;
        }

        public Graphics GetGraphics()
        {
            return gs;
        }

        public WriteableBitmap GetSource()
        {
            return wBitmap;
        }

        public Bitmap GetBitmap()
        {
            return backBitmap;
        }

        public Size GetSize()
        {
            return new Size(width, height);
        }

        public void Flush()
        {
            wBitmap.Lock();
            wBitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, width, height));
            wBitmap.Unlock();
        }

        public void Dispose()
        {
            backBitmap.Dispose();
            wBitmap = null;
            backBitmap = null;
        }
    }
}
